/*
 * Titre: PingBot
 * Device: MSP430g2211
 * Auteur: Farid Kilani
 * Date: 25/07/2012
 * Description: Programme MSP430 du projet robot PingBot. Il recoit un paquet IR RC5 d'une TV commande, le decode et pilote le robot en fonction.
 */


#include <msp430g2211.h>

#define Timer_value 45

unsigned char Add=1;
unsigned char Edge=1;		//Edge=0: value added during high to low; Edge=1: value added during low to high
unsigned char bit_pos=0;
unsigned char ignore=0;
unsigned char temp=0;
unsigned char instruction=0;
unsigned char value[14];

int main(void)
{
  WDTCTL = WDTPW + WDTHOLD;             // Stop watchdog timer

  P1DIR = 0xff;							// Set all pin to output
  P1DIR &= ~BIT3;						// Infra Red input
  P1IE = BIT3;							// Enable IR interrupt
  P1IES = BIT3;							// interrupt on low to high transition
  P1IFG=0;

  BCSCTL1 = XT2OFF+RSEL0+RSEL1+RSEL2+RSEL3;   // Set Max DCO
  DCOCTL = DCO0+DCO1+DCO2;

  TAR=0;									 // reset timer register
  TACTL=TASSEL_1 + MC_0;				     // ACLK source for TimerA, continious mode

  __bis_SR_register(LPM3_bits + GIE);        // LPM3 + enable interrupt
}



#pragma vector=PORT1_VECTOR
__interrupt void IR_reception (void)
{

  int i=0;
  P1IFG=0; 							// Clear interrupt flag
  TACTL=TASSEL_1 + MC_0;		    // stop timer

  //Security against noise or wrong packet
  if(TAR>120)
  {
	  bit_pos=0;
	  TAR=0;
	  Add=1;
	  Edge=1;
	  ignore=0;
	  instruction=0;
  }

  //ignore the last interrupt if the last bit of the previous packet is 1
  if(ignore==1)	  ignore=0;
  else
  {
	  if(P1IES!=0) P1IES=0;
	  else P1IES = BIT3;					// change interrupt edge selection*/
	  if(TAR>Timer_value) Add^=BIT0;	//change the value to be added (0 or 1)

	  if(Edge==Add)
	  {
		  value[bit_pos]=Add;
		  bit_pos++;
	  }
	  Edge^=BIT0;
	  TAR=0;							// reset timer register
	  TACTL=TASSEL_1 + MC_2;			// ACLK source for TimerA, continious mode
	  if(bit_pos==14)					// if we reach the bit 14, we reset everything and wait for another packet
	  {
		  if(Add==1) ignore=1;
		  bit_pos=0;
		  Add=1;
		  Edge=1;
		  TAR=0;
		  //decode instruction
		  for(i=13;i>8;i--)
		  {
			  temp=1;
			  temp=temp<<(13-i);
			  if(value[i]==0) instruction&=~temp;
			  else if(value[i]==1) instruction|=temp;
		  }
		  if(instruction==1) P1OUT=0xff;
		  else if (instruction==2) P1OUT=0;
		  P1IES=BIT3;
	  }
  }
}
